<template>
  <div class="v-flow-config-section">
    <div v-if="!isChild" class="config-section-title">设置表单权限</div>
    <el-table :data="filterTableData" style="width: 100%" height="300" border>
      <el-table-column label="表单项名称" prop="title">
        <template #header>
          <el-input v-model="search" size="small" placeholder="请输入表单项名称关键字" />
        </template>
      </el-table-column>
      <el-table-column label="可编辑" prop="isEdit">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isEdit"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="是"
            inactive-text="否"
            @change="changeEdit($event, scope.row, scope.$index)"
          >
          </el-switch>
          <!-- 子表单权限配置 -->
          <el-popover placement="bottom" :width="460" trigger="click">
            <FormConfig
              v-if="scope.row.childs"
              :formData="scope.row.childs"
              :inputKey="scope.row.inputKey"
              :isChild="true"
              @update="update"
            />
            <template #reference>
              <el-link
                type="primary"
                v-if="scope.row.childs && scope.row.childs.length > 0"
                style="margin: 0 20px"
              >
                多行表格
              </el-link>
            </template>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import type { FormConfig } from '../types'
const props = defineProps({
  formData: {
    type: Object as () => FormConfig[],
    default: () => {
      return []
    }
  },
  isChild: {
    type: Boolean,
    default: false
  },
  inputKey: {
    type: String,
    default: ''
  }
})
const emits = defineEmits(['update'])
// 表单项关键词搜索
const search = ref<string>('')
const filterTableData = computed(() => {
  return props.formData.filter(
    (data) => !search.value || data.title.toLowerCase().includes(search.value.toLowerCase())
  )
})

// 切换是否可编辑
const changeEdit = (val: string | number | boolean, row: FormConfig, index: number) => {
  const isEdit = val as boolean
  const formData = props.formData.map((el, i) => {
    if (i === index) {
      el.isEdit = isEdit
    }
    return el
  })
  emits('update', { formData })
}

// 更新子表单数据
const update = ({ formData, inputKey }: { formData: FormConfig[]; inputKey: string }) => {
  if (inputKey) {
    const arr = props.formData.map((el, i) => {
      if (el.inputKey === inputKey) {
        el.childs = formData
      }
      return el
    })
    emits('update', { formData: arr, inputKey: props.inputKey })
  }
}
</script>

<script lang="ts">
export default {
  name: 'FormConfig'
}
</script>

<style scoped></style>
